package com.xinpujing.caiji.service;

import com.alibaba.fastjson.JSONObject;
import com.xinpujing.caiji.dto.api68.Api68Dto;
import com.xinpujing.caiji.dto.api68.Data;
import com.xinpujing.caiji.dto.opencai.OpenCaiDto;
import com.xinpujing.caiji.enums.LotteryTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketTimeoutException;

import static com.xinpujing.caiji.util.HttpUtils.getString;
import static com.xinpujing.caiji.util.HttpUtils.getStringWithUserAgent;

/**
 *  http://apilottery.com/
 */
public class ApiLotteryService {

    private static Logger logger = LoggerFactory.getLogger(ApiLotteryService.class);

    private CommonService commonService;

    public void insertIfNotExist(String url , LotteryTypeEnum typeEnum){
        int type = typeEnum.getType();
        if(url.equals("")){
            logger.info("url is null , ignore , type {}" , typeEnum.getName());
            return;
        }
        if(type == 0){
            logger.info("type is 0 , ignore , url {} name {} " , url , typeEnum.getName());
            return;
        }
        String jsonStr = null;
        try{
            jsonStr = getStringWithUserAgent(url);
        }catch (SocketTimeoutException e){
            logger.error("socket time out .. {}" , url );
            return;
        }

        OpenCaiDto caiDto =  JSONObject.parseObject(jsonStr , OpenCaiDto.class);

        if(caiDto.getData() == null){
            logger.error("data is null  .. {}" , url );
            return;
        }
        for(com.xinpujing.caiji.dto.opencai.Data temp : caiDto.getData()){
            String number = temp.getExpect();
            String time = temp.getOpentime();
            String data = temp.getOpencode();

            Boolean exist = commonService.exist(type  , number , data );
            if(exist){
                logger.trace(" 开奖数据已存在 ..type {}  , time {} , number {} , data {}  " , type , time , number , data);
                continue;
            }
            commonService.insert(type ,  time , number , data );
            logger.info(" 开奖数据已录入 ..type {}  , time {} , number {} , data {}  " , typeEnum.getName() , time , number , data);
        }

    }

    public CommonService getCommonService() {
        return commonService;
    }

    public void setCommonService(CommonService commonService) {
        this.commonService = commonService;
    }
}
